<?php

namespace App\Admin\Controllers;

use App\Models\WxCustomMenu;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\MessageBag;

/**
 * Class WxCustomMenuController
 * @package App\Admin\Controllers
 * 微信自定义菜单
 */
class WxCustomMenuController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('自定义菜单');
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('自定义菜单');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(WxCustomMenu::class, function (Grid $grid) {

            //id, url, title, pid, sort, type

            $grid->id('ID')->sortable();
            $grid->pid('父级菜单')->display(function ($data){
                if($data==0){
                    return '一级菜单';
                }
                return WxCustomMenu::where('id',$data)->value('title');
            });
            $grid->type('类型');
            $grid->title('标题（5个字符）');
            $grid->sort('排序');
            $grid->url('链接');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(WxCustomMenu::class, function (Form $form) {
            $form->tools(function (Form\Tools $tools) {
                // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                $tools->add('<a class="btn btn-sm btn-danger" href="'.url('admin/currentMenu').'">查看当前自定义菜单</a>');
                $tools->add('<a class="btn btn-sm btn-danger" href="'.url('admin/updateMenu').'">发布菜单</a>');

            });
            $form->display('id', 'ID');
            $optionsObj=WxCustomMenu::where('pid',0)->get();
            $optionsArr[0]='一级菜单';
            foreach ($optionsObj as $v){
                $optionsArr[$v->id]=$v->title;
            }
            $form->select('pid')->options($optionsArr);
            $form->select('type')->options(['view' => '网页','more'=>'多级菜单（不填写url）']);
            $form->text('title','标题（5个字符以内）');
            $form->number('sort','排序');
            $form->url('url','链接')->default('http://');

        });
    }

    //查看当前自定义菜单
    public function currentMenu(){

        $menus = app('wechat')->menu->current();
        echo '<pre>';
        print_r($menus);
        echo '<pre/>';
    }
    //更新微信菜单
    public function updateMenu(){
        $data=WxCustomMenu::OrderBy('sort','asc')->get();
        /* // 全部*/
        $bottons=[];
        foreach($data as $k=>$v){
            if($v->pid==0){
                $tmp=[];
                //一级菜单
                if($v->type!='more'){
                    $tmp['type']=$v->type;
                    $tmp['url']=$v->url;
                }
                $tmp['name']=$v->title;
                $tmp['id']=$v->id;
                $bottons[]=$tmp;
                unset($data->$k);//用了则删除
            }
        }

        foreach ($bottons as $k=>$v){
            foreach ($data as $k1=> $v1){
                if($v1->pid==$v['id']){
                    $tmp['type']=$v1->type;
                    $tmp['name']=$v1->title;
                    $tmp['url']=$v1->url;
                    $tmp['id']=$v1->id;
                    $bottons[$k]['sub_button'][]=$tmp;
                    unset($data->$k1);
                }
            }
        }
        if(count($bottons)!=0){
            $wechat=app('wechat');
            $menu = $wechat->menu;
            $menu->destroy();
            $res=$menu->add($bottons);
            if($res){
                $success = new MessageBag([
                    'title'   => '自定义菜单',
                    'message' => '更新成功',
                ]);

                return back()->with(compact('success'));
            }else{
                $error = new MessageBag([
                    'title'   => '自定义菜单',
                    'message' => '更新失败',
                ]);

                return back()->with(compact('error'));
            }

        }

    }
}
